package com.xiaobai.frame.config.aspect;

import com.xiaobai.common.utils.config.log.Log;
import com.xiaobai.common.utils.tool.AuthUtil;
import com.xiaobai.common.utils.tool.StringUtils;
import com.xiaobai.common.utils.tool.UserInfo;
import com.xiaobai.common.utils.tool.WebUtil;
import com.xiaobai.model.enums.BusinessStatus;
import com.xiaobai.frame.service.IOperLogService;
import com.xiaobai.model.entity.system.OperLog;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 用于拦截方法名带有"query"前缀的方法的查询方法进行字典表字段转换(用于在VO当中)
 */
@Aspect
@Component
@RequiredArgsConstructor
public class LogAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
    private final IOperLogService iOperLogService;
    @Pointcut("@annotation(com.xiaobai.common.utils.config.log.Log)")
    public void doPointcut() {
    }
    /**
     * 处理完请求后执行
     */
    @Before("doPointcut()")
    public void doBefore() {

    }

    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "@annotation(log)", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Log log, Object jsonResult) {
        handleLog(joinPoint, log, null, jsonResult);
    }

    /**
     * 拦截异常操作   未绑定的切入点形参 'controllerLog'
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "@annotation(log)", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Log log, Exception e) {
        handleLog(joinPoint, log, e, null);
    }

    protected void handleLog(final JoinPoint joinPoint, Log log, final Exception e, Object jsonResult) {
        try {
            // *========数据库日志=========*//
            OperLog operLog = new OperLog();
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());
            // 请求的地址
            String ip = WebUtil.getIP();
            operLog.setOperIp(ip);
            operLog.setOperUrl(StringUtils.substring(WebUtil.getRequest().getRequestURI(), 0, 255));
            UserInfo user = AuthUtil.getUser();
            operLog.setOperName(String.valueOf(user.getId()));
            operLog.setDeptName(user.getDeptId());

            if (e != null) {
                operLog.setStatus(BusinessStatus.FAIL.ordinal());
                operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");
            // 设置请求方式
            operLog.setRequestMethod(WebUtil.getRequest().getMethod());
            // 设置action动作
            operLog.setBusinessType(log.businessType().ordinal());
            // 设置标题
            operLog.setTitle(log.title());
            // 发布事件保存数据库
            iOperLogService.saveData(operLog);
        } catch (Exception exp) {
            // 记录本地异常日志
            logger.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }
}
